package com.yint.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;

import com.yint.core.AbsSocketReactor;
import com.yint.core.Handler;

public class TCPReactor extends AbsSocketReactor {

	private ServerSocketChannel ssc;
	private Selector selector;
	private int port;
	private Handler handler;

	public TCPReactor(int port) {
		this.port = port;
	}

	@Override
	protected void onStart() throws IOException {
		System.out.println("TCPReactor onStart");
		selector = Selector.open();
		ssc = ServerSocketChannel.open();
		InetSocketAddress addr = new InetSocketAddress(port);
		// 在ServerSocketChannel绑定监听端口
		ssc.socket().bind(addr);
		// 设置ServerSocketChannel为非阻塞
		ssc.configureBlocking(false);
		// ServerSocketChannel向selector注册一个OP_ACCEPT事件，然后返回该通道的key
		ssc.register(selector, SelectionKey.OP_ACCEPT);
		handler = new Acceptor(selector, ssc);
	}

	@Override
	protected void onStop() {

	}

	@Override
	protected Selector getSelector() {
		return selector;
	}

	@Override
	protected void dispatch(SelectionKey selectedKey) throws IOException {
		if (handler != null) {
			handler.handle(selectedKey);
		}
	}

}
